package com.file.parser;

import com.file.bo.ResponseData;
import com.file.bo.Taxi;
import com.file.bo.Taxi2;
import com.file.bo.TaxiTran;
import com.file.bo.TaxiTran2;
import com.file.constant.ErrorCode;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 个税申报收入明细解析
 * @author anyspa
 */

@Slf4j
public class TaxiHtmlParser {

    public ResponseData<String> parseTaxiHtmlToJson(String daId, String filePath) {
        log.info("parseTaxiToJson started, daId:{}", daId);
        String json;
        try {
            Document doc = Jsoup.parse(new File(filePath), "UTF-8");
            // 纳税人信息
            Elements elements = doc.select(".nsr-info");
            if (elements.size() > 0) {
                // 老版个税申报收入
                Taxi taxi = parseTaxiHtmlOldVersionToJson(filePath);
                json = JsonUtils.convertObjectToJson(taxi);
            } else {
                // 新版个税申报收入
                Taxi2 taxi2 = parseTaxiHtmlNewVersionToJson(daId, filePath);
                json = JsonUtils.convertObjectToJson(taxi2);
            }
        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseTaxiToJson failed", e);
            return new ResponseData<>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(),
                    ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseTaxiToJson completed, daId:{}, json:{}", daId, json);
        return new ResponseData<>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    private Taxi parseTaxiHtmlOldVersionToJson(String filePath) throws IOException {
        File input = new File(filePath);
        Taxi taxi = new Taxi();
        List<TaxiTran> taxiTrans = new ArrayList<>();

        Document doc = Jsoup.parse(input, "UTF-8");

        // 纳税人信息
        Elements elements = doc.select(".nsr-info > div > span");

        elements.forEach(element -> {
            if (element.hasAttr("tax-text")) {
                String attrValue = element.attr("tax-text");
                if (StringUtils.isNotBlank(attrValue)) {
                    if (attrValue.contains("nsrsbh")) {              // 纳税人识别号
                        taxi.setTaxpayerIdentifier(element.text());
                    } else if (attrValue.contains("nsrmc")) {        // 纳税人名称
                        taxi.setTaxpayerName(element.text());
                    } else if (attrValue.contains("sfzjlx")) {       // 身份证件类型
                        taxi.setIdCardType(element.text());
                    } else if (attrValue.contains("sfzjhm")) {       // 身份证件号码
                        taxi.setIdNo(element.text());
                    }
                }
            }
        });

        // 税款所属期
        Elements taxPeriodElements = doc.select(".query-condition .its-input-datepicker > input");
        if (taxPeriodElements.size() == 2) {
            String taxPeriodStartDate = taxPeriodElements.get(0).attr("value");
            String taxPeriodEndDate = taxPeriodElements.get(1).attr("value");
            taxi.setTaxPeriod(taxPeriodStartDate.concat("至").concat(taxPeriodEndDate));
        }

        // 申报收入合计 & 申报税额合计
        Elements taxAmountElements = doc.select(".nsmxlb-statistical .div-amount");
        if (taxAmountElements.size() == 2) {
            taxi.setDeclareIncomeTotal(taxAmountElements.get(0).text());
            taxi.setDeclareTaxTotal(taxAmountElements.get(1).text());
        }

        Elements taxRowElements = doc.select(".its-table .its-row.row-highlight");
        taxRowElements.forEach(element -> {
            TaxiTran taxiTran = new TaxiTran();
            Elements colElements = element.getElementsByAttributeValueMatching("style", "text-align");
            if (colElements.size() == 8) {
                taxiTran.setIncomeItem(colElements.get(0).text());
                taxiTran.setTaxPeriod(colElements.get(1).text());
                taxiTran.setDeclarationDate(colElements.get(2).text());
                taxiTran.setDeclarationFormType(colElements.get(3).text());
                taxiTran.setIncome(colElements.get(4).text());
                taxiTran.setTaxPayableRefundable(colElements.get(5).text());
                taxiTran.setWithholdAgent(colElements.get(6).text());
                taxiTran.setOperate(colElements.get(7).text());

                taxiTrans.add(taxiTran);
            }
        });

        taxi.setTaxiTrans(taxiTrans);
        log.info(taxi.toString());
        return taxi;
    }

    private Taxi2 parseTaxiHtmlNewVersionToJson(String daId, String filePath) throws IOException {
        File input = new File(filePath);
        Taxi2 taxi = new Taxi2();
        List<TaxiTran2> taxiTrans = new ArrayList<>();

        Document doc = Jsoup.parse(input, "UTF-8");

        // 收入合计
        Element incomeTotalElement = doc.selectFirst(".income-tax-query > div:nth-child(2) > .srnsmx-page .div1");
        if (incomeTotalElement != null && incomeTotalElement.selectFirst(".content") != null) {
            taxi.setIncomeTotal(incomeTotalElement.selectFirst(".content").text());
        }

        // 已申报税额合计
        Element declaredTaxTotalElement = doc.selectFirst(".income-tax-query > div:nth-child(2) > .srnsmx-page .div2");
        if (declaredTaxTotalElement != null && declaredTaxTotalElement.selectFirst(".content") != null) {
            taxi.setDeclaredTaxTotal(declaredTaxTotalElement.selectFirst(".content").text());
        }

        // 个税申报收入明细
        Elements taxiTranElements = doc.select(".income-tax-query > div:nth-child(2) > .srnsmx-page >.table-container .el-table__row");
        for (Element element : taxiTranElements) {
            TaxiTran2 taxiTran = new TaxiTran2();
            Elements cellElements = element.select(".cell");
            if (cellElements.size() == 9) {
                taxiTran.setIncomeItem(cellElements.get(0).text());
                taxiTran.setTaxPeriodStartDate(cellElements.get(1).text());
                taxiTran.setTaxPeriodEndDate(cellElements.get(2).text());
                taxiTran.setDeclarationDate(cellElements.get(3).text());
                taxiTran.setDeclarationFormType(cellElements.get(4).text());
                taxiTran.setCurrentIncome(cellElements.get(5).text());
                taxiTran.setDeclaredTax(cellElements.get(6).text());
                taxiTran.setIncomeSourceUnit(cellElements.get(7).text());
                taxiTran.setOperate(cellElements.get(8).text());

                taxiTrans.add(taxiTran);
            } else {
                log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "Taxi html of new version has changed");
            }
        }

        taxi.setTaxiTrans(taxiTrans);
        log.info(taxi.toString());
        return taxi;
    }


    public static void main(String[] args) {
        TaxiHtmlParser taxeHtmlParser = new TaxiHtmlParser();
//        String filePath = "D:\\data\\file\\taxi\\zd1tuknz1562357061382291456_24a5ba47d5ce2eb3cdc22309be8f6dbe_taxi_nsmxlb2022-1-old.html";
         String filePath = "D:\\data\\file\\taxi\\zd1tuknz1572777936392798208_42cdb72f3adca42074d82187e8fa3d6e_taxi_nsmxlb.html";
        String json = taxeHtmlParser.parseTaxiHtmlToJson("", filePath).getData();

        System.out.println(json);

    }
}
